package com.flyco.modules.returns.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.common.api.vo.Result;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.system.vo.DictModel;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.RedisUtil;
import com.flyco.common.util.RestUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.cms.entity.CmsImageTag;
import com.flyco.modules.cms.entity.CmsImageTagProduct;
import com.flyco.modules.cms.vo.CmsImageTagPage;
import com.flyco.modules.oms.entity.OmsOrder;
import com.flyco.modules.oms.entity.OmsOrderItem;
import com.flyco.modules.oms.entity.OmsOrderTrace;
import com.flyco.modules.oms.model.OmsOrderModel;
import com.flyco.modules.oms.service.IOmsOrderService;
import com.flyco.modules.oms.service.IOmsOrderTraceService;
import com.flyco.modules.oms.vo.OmsSendOrderDto;
import com.flyco.modules.oms.vo.OmsSendOrderItem;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.returns.entity.*;
import com.flyco.modules.returns.service.*;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.system.service.ISysDictService;
import com.flyco.modules.ums.model.UmsMemberReceiveAddressModel;
import com.flyco.modules.ums.service.IUmsMemberReceiveAddress;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.record.PageBreakRecord;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 申请退换货
 * @Author: flyco
 * @Date: 2023-08-01
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "申请退换货")
@RestController
@RequestMapping("/f/returns/omsOrderReturnApply")
public class OmsOrderReturnApplyController extends BaseController<OmsOrderReturnApply, IOmsOrderReturnApplyService> {
    @Autowired
    private IOmsOrderReturnApplyService omsOrderReturnApplyService;
    @Autowired
    private IOmsOrderTraceService omsOrderTraceService;
    @Autowired
    private IOmsOrderReturnItemService returnItemService;
    @Autowired
    private IOmsOrderReturnApplyOmsService returnApplyOmsService;
    @Autowired
    private ISysDictService dictService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IPmsProductService productService;

    /**
     * 分页列表查询
     *
     * @param omsOrderReturnApply
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "申请退换货-分页列表查询")
    @ApiOperation(value = "申请退换货-分页列表查询", notes = "申请退换货-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OmsOrderReturnApply omsOrderReturnApply,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        if (omsOrderReturnApply.getStoreName() != null && omsOrderReturnApply.getStoreName().indexOf("*") == -1) {
            omsOrderReturnApply.setStoreName("*" + omsOrderReturnApply.getStoreName() + "*");
        }
        QueryWrapper<OmsOrderReturnApply> queryWrapper = QueryGenerator.initQueryWrapper(omsOrderReturnApply, req.getParameterMap());
        Page<OmsOrderReturnApply> page = new Page<OmsOrderReturnApply>(pageNo, pageSize);
        IPage<OmsOrderReturnApply> pageList = omsOrderReturnApplyService.page(page, queryWrapper);


        return Result.ok(pageList);
    }

    /**
     * 售后审批
     */
    @AutoLog(value = "售后物流审批")
    @ApiOperation(value = "售后物流审批", notes = "售后物流审批")
    @PostMapping(value = "/approve")
    public Result<?> approve(@RequestBody OrderReturnApproveDTO returnApproveDTO) {

        Result result = omsOrderReturnApplyService.logisticsApprove(returnApproveDTO);

        if (!result.getMessage().equals("审批完成")) {
            return result;
        }

        OmsOrderReturnApply returnApplyInfo = omsOrderReturnApplyService.getById(returnApproveDTO.getId());
        if (!returnApplyInfo.getStatus().equals(4)) {
            sendMsgForReturnApprove(returnApplyInfo.getId().toString());
        }
        return Result.ok("审批完成！");
    }

    /**
     * 售后审批
     */
    @AutoLog(value = "售后品检员审批")
    @ApiOperation(value = "售后品检员审批", notes = "售后品检员审批")
    @PostMapping(value = "/inspectionApprove")
    public Result<?> inspectionApprove(@RequestBody OrderReturnApproveDTO returnApproveDTO) {

        Result result = omsOrderReturnApplyService.inspectionApprove(returnApproveDTO);
        if (!result.getMessage().equals("审批完成")) {
            return result;
        }

        OmsOrderReturnApply returnApplyInfo = omsOrderReturnApplyService.getById(returnApproveDTO.getId());
        if (!returnApplyInfo.getStatus().equals(4)) {
            sendMsgForReturnApprove(returnApplyInfo.getId().toString());
        }
        return Result.ok("审批完成！");
    }

    /**
     * 售后审批
     */
    @AutoLog(value = "售后跟单员审批")
    @ApiOperation(value = "售后跟单员审批", notes = "售后跟单员审批")
    @PostMapping(value = "/orderManagerApprove")
    public Result<?> orderManagerApprove(@RequestBody OrderReturnApproveDTO returnApproveDTO) {

        Result result = omsOrderReturnApplyService.orderManagerApprove(returnApproveDTO);
        if (!result.getMessage().equals("审批完成")) {
            return result;
        }
        OmsOrderReturnApply returnApplyInfo = omsOrderReturnApplyService.getById(returnApproveDTO.getId());
        // 把退货申请进行报废和分仓的分单处理
        if (Objects.equals(returnApplyInfo.getReturnType(), 1)) {
            returnApplyOmsService.savaByApplyId(returnApplyInfo.getId());
        }
        return Result.ok("审批完成！");
    }


    /**
     * 财务审批：补发审核
     */
    @AutoLog(value = "财务审批")
    @ApiOperation(value = "财务审批", notes = "财务审批")
    @PostMapping(value = "/financeApprove")
    public Result<?> financeApprove(@RequestBody OrderReturnApproveDTO returnApproveDTO) {

        return omsOrderReturnApplyService.financeApprove(returnApproveDTO);
    }

    /**
     * 编辑
     *
     * @param omsOrderReturnApply
     * @return
     */
    @AutoLog(value = "申请退换货-编辑")
    @ApiOperation(value = "申请退换货-编辑", notes = "申请退换货-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OmsOrderReturnApply omsOrderReturnApply) {
        omsOrderReturnApplyService.updateById(omsOrderReturnApply);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "申请退换货-通过id删除")
    @ApiOperation(value = "申请退换货-通过id删除", notes = "申请退换货-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        omsOrderReturnApplyService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "申请退换货-批量删除")
    @ApiOperation(value = "申请退换货-批量删除", notes = "申请退换货-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.omsOrderReturnApplyService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "申请退换货-通过id查询")
    @ApiOperation(value = "申请退换货-通过id查询", notes = "申请退换货-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OmsOrderReturnApply omsOrderReturnApply = omsOrderReturnApplyService.getById(id);
        return Result.ok(omsOrderReturnApply);
    }

    /**
     * 导出退货申请及明细，先查询出申请记录，然后在跟申请记录的明细组合后返回
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OmsOrderReturnApply omsOrderReturnApply) {
        // Step.1 组装查询条件
        QueryWrapper<OmsOrderReturnApply> queryWrapper = QueryGenerator.initQueryWrapper(omsOrderReturnApply, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<OmsOrderReturnApplyExcel> excelList = new ArrayList<>();
        List<OmsOrderReturnApply> applyList = omsOrderReturnApplyService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(applyList)) {

            List<Long> applyId = applyList.stream().map(o -> o.getId()).collect(Collectors.toList());
            LambdaQueryWrapper<OmsOrderReturnItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(OmsOrderReturnItem::getReturnApplyId, applyId);
            Map<Long, List<OmsOrderReturnItem>> itemMap = returnItemService.list(wrapper)
                    .stream()
                    .collect(Collectors.groupingBy(OmsOrderReturnItem::getReturnApplyId));

            applyList.forEach(o -> {
                List<OmsOrderReturnItem> itemList = itemMap.get(o.getId());
                itemList.forEach(item -> {
                    OmsOrderReturnApplyExcel applyExcel = new OmsOrderReturnApplyExcel();
                    BeanUtils.copyProperties(o, applyExcel);
                    applyExcel.setProductCount(item.getProductCount());
                    applyExcel.setProductName(item.getProductName());
                    applyExcel.setProductSkuCode(item.getProductSkuCode());
                    applyExcel.setPrice(item.getPrice());
                    applyExcel.setTotalAmount(item.getTotalAmount());
                    excelList.add(applyExcel);
                });
            });
        }

        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "退货申请报表");
        mv.addObject(NormalExcelConstants.CLASS, OmsOrderReturnApplyExcel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("退货申请报表", "导出人:" + sysUser.getRealname(), "退货申请报表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, excelList);
        return mv;

    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OmsOrderReturnApply.class);
    }

    /**
     * 查询订单跟踪信息
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单-查询订单跟踪信息")
    @GetMapping(value = "/queryOmsReturnOrderTrace")
    public Result<?> queryOmsReturnOrderTrace(@RequestParam(name = "id", required = true) String id) {
        OmsOrderReturnApply returnApply = omsOrderReturnApplyService.getById(id);
        if (null == returnApply) return Result.error("查询的退单不存在");
        LambdaQueryWrapper<OmsOrderTrace> query = new LambdaQueryWrapper<>();
        query.eq(OmsOrderTrace::getOrderId, id);
        if (oConvertUtils.isNotEmpty(returnApply.getDeliverySn())) {
            query.or();
            query.eq(OmsOrderTrace::getTraceNo, returnApply.getDeliverySn());
        }
        query.orderByDesc(OmsOrderTrace::getId);
        List<OmsOrderTrace> traceList = omsOrderTraceService.list(query);
        traceList.forEach(o -> {
            if (o.getLabel().equals("补发订单")) {
                o.setContent(o.getContent() + ",请在[个人中心-我的订单]中查看");
            }
        });
        return Result.ok(traceList);
    }

    private void sendMsgForReturnApprove(String returnApplyId) {
        try {
            DictModel dictModel = dictService.queryDictItemsByCode("msgAddress").get(0);
            String msgUrl = dictModel.getValue() + "/api/back/0-0/sendSms/returnsOrder/" + returnApplyId;
            RestUtil.get(msgUrl);
        } catch (Exception ex) {
            log.error("sendMsgForReturnApprove 异常。msg=" + ex.getMessage());
        }
    }

    @AutoLog(value = "获取退单打印地址")
    @ApiOperation(value = "获取退单打印地址")
    @GetMapping(value = "/getReturnOrderPrintUrl")
    public Result<?> getPrintUrl() {
        String key = "returnOrderUrl";
        String url = (String) redisUtil.get(key);
        if (StringUtils.isEmpty(url)) {
            DictModel dictModel = dictService.queryDictItemsByCode("returnOrderPrint").get(0);
            if (dictModel == null) {
                url = "";
            }
            url = dictModel.getValue();
            redisUtil.set(key, url);
        }
        return Result.ok(url);
    }


    @AutoLog(value = "获取商品列表,供退货时选择")
    @ApiOperation(value = "获取商品列表,供退货时选择")
    @GetMapping(value = "/getOrderReturnProductList")
    public Result<?> getOrderReturnProductList(@RequestParam("storeId") Long storeId,
                                               @RequestParam("productName") String productName,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        Integer beginIndex = (pageNo - 1) * pageSize;
        IPage<PmsProduct> pageList = new Page<>();
        pageList.setSize(pageSize);
        pageList.setPages(pageNo);
        pageList.setTotal(0);
        List<PmsProduct> productList = productService.getProductListByName(productName);
        if (!CollectionUtils.isEmpty(productList)) {
            pageList.setTotal(productList.size());
            List<PmsProduct> productList2 = productList.stream().skip(beginIndex).limit(pageSize).collect(Collectors.toList());
            pageList.setRecords(productList2);
        }
        return Result.success(pageList);
    }


    @AutoLog(value = "退回其他人进行审核")
    @ApiOperation(value = "退回其他人进行审核", notes = "退回其他人进行审核")
    @PostMapping(value = "/returnPreApprove")
    public Result<?> returnPreApprove(@RequestBody OrderReturnApproveDTO returnApproveDTO) {

        return omsOrderReturnApplyService.returnPreApprove(returnApproveDTO);
    }
}
